import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Switch, Image } from 'antd';
import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProForm, { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { addAdmin, adminList, roleSelect, updataPassword, updateAdmin } from './service';
import type { TableListItem, TableListPagination } from './data';
import { formatTime } from '@/utils/index';
import { checkPassword } from '@/utils/rolue'
import ImgUpload from '@/components/ossUpload'
import { userStatus, userGender } from '@/constant/constant';
import Handle from '../components/Handle';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: TableListItem) => {
    const hide = message.loading('正在添加');

    try {
        await addAdmin({ ...fields, meta: { role_id: fields.role_id } });
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};


/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: any, currentRow?: TableListItem) => {
    const hide = message.loading('正在修改');

    try {
        await updateAdmin({
            guid: currentRow?.guid,
            avatar: currentRow?.currentRow,
            ...fields,
            meta: { role_id: fields.role_id }
        });
        hide();
        message.success('修改成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};

/**
 * 修改密码
 * @param fields
 * @param currentRow
 * @returns
 */
const handlePasswordUpdate = async (fields: any, currentRow?: TableListItem) => {
    const hide = message.loading('正在修改');

    try {
        await updataPassword({
            guid: currentRow?.guid,
            ...fields,
        });
        hide();
        message.success('修改成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};


// 添加或者修改密码表单
const passWordBOX = () => (<>
    <ProFormText.Password

        fieldProps={
            {
                autocomplete: "new-password"
            }
        }
        rules={[
            {
                required: true,
                message: '用户密码为必填项',
            },
            ({ getFieldValue }: any) => ({
                validator(role: any, value: string) {
                    const password_value = getFieldValue('passwords')
                    if (password_value && password_value !== value) {
                        return Promise.reject('两次密码不一致')
                    }
                    return Promise.resolve()
                }
            })
        ]}
        width="md"
        name="password"
        label="用户密码"
    />
    <ProFormText.Password
        rules={[
            {
                required: true,
                message: '请确认密码',
            },
            ({ getFieldValue }: any) => ({
                validator(role: any, value: string) {
                    const password_value = getFieldValue('password')
                    if (password_value && password_value !== value) {
                        return Promise.reject('两次密码不一致')
                    }
                    return Promise.resolve()
                }
            })
        ]}
        width="md"
        name="passwords"
        label="确认密码"
    />
</>)

// 修改或添加表单 name role avatar
const EditBox = () => (<>
    <ProFormText
        rules={[
            {
                required: true,
                message: '用户名称为必填项',
            },
        ]}
        width="md"
        name="nick_name"
        label="用户昵称"
    />
    <ProForm.Item
        name="avatar"
        label="头像"
        rules={[
            {
                required: true,
                message: '请上传头像',
            },
        ]}>
        <ImgUpload needCrop={true} cropProps={{ aspect: 1 / 1, rotate: true }} maxSize={0.5} pictureQuality={0.7} />
    </ProForm.Item>
    <ProFormSelect
        name="role_id"
        label="角色名称"
        showSearch
        width="md"
        debounceTime={300}
        request={async ({ keyWords }) => {
            try {
                const data = await roleSelect({ name: keyWords })
                return data.map((item: { guid: string, name: string }) => {
                    return {
                        value: item.guid,
                        label: item.name
                    }
                })

            } catch (error) {
                return []
            }

        }}
        placeholder="请选择角色,输入可搜索"
        rules={[{ required: true, message: '请选择角色' }]}
    />
</>)

const TableList: React.FC = () => {
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);

    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [updatePasswordModalVisible, handleupdatePasswordModalVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<TableListItem>();
    const handleRef: any = useRef<ActionType>();
    const actionRef = useRef<ActionType>();

    const handle = (type: string, key: string, data?: object) => {

        handleRef && handleRef.current.handle(type, key, data);
    };

    // 操作回调 刷新信息
    const refresh = () => {
        actionRef && actionRef.current && actionRef.current.reload();
    };

    const columns: ProColumns<TableListItem>[] = [
        {
            title: '用户编号',
            dataIndex: 'guid',
            ellipsis: true,
            copyable: true,
        },
        {
            title: '登录账号',
            dataIndex: 'username',
        },
        {
            title: '用户头像',
            search: false,
            render: (val: any) => val.avatar ? <Image width={60} height={60} src={val.avatar} /> : '-',
        },
        {
            title: '用户昵称',
            dataIndex: 'nick_name',
            ellipsis: true,
            render: (_, val: any) => < a href={'/customer/detail?id=' + val.guid} >{val.nick_name}</a >
        },
        {
            title: '性别',
            dataIndex: 'gender',
            valueEnum: userGender,
        },
        {
            title: '绑定手机',
            dataIndex: 'bind_phone',
            ellipsis: true,
        },
        {
            title: '角色',
            dataIndex: 'role_id',
            valueType: 'select',
            fieldProps: {
                fieldNames: { label: 'name', value: 'guid' },
            },
            request: async (params) => roleSelect({}),
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueEnum: userStatus,
            render: (_, val) => <>
                <Switch
                    checkedChildren="正常" unCheckedChildren="禁用"
                    onClick={() => {
                        if (val.status == 1) {
                            handle('disable', val.guid, val)
                        } else {
                            handle('enable', val.guid, val)
                        }
                    }}
                    checked={val.status === 1}
                />
            </>
        },
        {
            title: '最后登录时间',
            dataIndex: 'user_token',
            search: false,
            render: (val: any) => <span>{formatTime(val?.last_time)}</span>,
        },
        {
            title: '注册时间',
            dataIndex: 'created_at',
            search: false,
            valueType: 'dateTime',
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            width: 140,
            render: (_: any, record: TableListItem) => [
                <a
                    key="config"
                    onClick={() => {
                        setCurrentRow({ ...record, role_id: record.meta?.role_id });
                        handleUpdateModalVisible(true);
                    }}
                >
                    编辑
                </a>,
                <a
                    key="password"
                    onClick={() => {
                        setCurrentRow(record);
                        handleupdatePasswordModalVisible(true);
                    }}
                >
                    修改密码
                </a>
            ],
        },
    ];


    return (
        <PageContainer>
            <ProTable<TableListItem>
                headerTitle="查询表格"
                actionRef={actionRef}
                rowKey="guid"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined /> 新建
                    </Button>,
                ]}
                params={{ type: 2 }}
                request={async (params) => {
                    let res = await adminList(params);

                    res.data = res.data.map((item: any) => ({
                        ...item,
                        role_id: item.meta?.role_id
                    }));
                    return res;
                }}
                columns={columns}
            />

            {/* 新建modal */}
            <ModalForm
                title="新建"
                width="600px"
                visible={createModalVisible}
                onVisibleChange={handleModalVisible}
                modalProps={{
                    destroyOnClose: true
                }}
                onFinish={async (value) => {

                    const success = await handleAdd({ avatar: '', ...value } as TableListItem);
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '账号为必填项',
                        },
                        () => ({
                            validator(role: any, value: string) {
                                const data = checkPassword(value, '账号', 5)
                                if (!data.status) {
                                    return Promise.reject(data.massage)
                                }
                                return Promise.resolve()
                            }
                        })
                    ]}
                    width="md"
                    name="username"
                    label="账号"
                />
                {/* 与编辑组件重复抽离 */}
                {EditBox()}
                {/* 与密码组件重复抽离 */}
                {passWordBOX()}
            </ModalForm>

            {/* 编辑 */}
            <ModalForm
                title="编辑"
                width="600px"
                visible={updateModalVisible}
                onVisibleChange={handleUpdateModalVisible}
                modalProps={{
                    destroyOnClose: true
                }}
                initialValues={{
                    ...currentRow,
                }}

                onFinish={async (value) => {
                    const success = await handleUpdate(value, currentRow);
                    if (success) {
                        handleUpdateModalVisible(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                {EditBox()}
            </ModalForm>

            {/* 修改密码 */}
            <ModalForm
                title="编辑"
                width="600px"
                visible={updatePasswordModalVisible}
                onVisibleChange={handleupdatePasswordModalVisible}
                initialValues={{
                    password: '',
                    passwords: ''
                }}
                modalProps={{
                    destroyOnClose: true
                }}
                onFinish={async (value) => {
                    const success = await handlePasswordUpdate(value, currentRow);

                    if (success) {
                        handleupdatePasswordModalVisible(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                {passWordBOX()}
            </ModalForm>

            <Handle ref={handleRef} callback={refresh} />
        </PageContainer>
    );
};

export default TableList;
